#include "threadPool.h"

int exitPipe[2];
void handler(int signum)
{
    printf("signum = %d\n",signum);
    write(exitPipe[1],"1",1);
}



int main(int argc,char *argv[])
{
    //ARGS_CHECK(argc,4);
    //解析conf文件
    FILE *fp_conf = fopen(argv[1],"r");
    char str[1024];
    if(fp_conf != NULL)
    {
        if(fgets(str,1024,fp_conf) != NULL)
        {
            printf("得到了str\n");
        }
        fclose(fp_conf);
    }
    else
    {
         printf("打开文件失败\n");
    }

    char *token = strtok(str, " ");

    char *conf[3];
    int i=0;
    while(token != NULL)
    {
       conf[i] = token;
       ++i;
       token = strtok(NULL," ");
    }




    pipe(exitPipe);
    if(fork() != 0)
    {
        printf("pid = %d\n",getpid());
        close(exitPipe[0]);
        signal(SIGUSR1,handler);
        wait(NULL);
        exit(0);
    }
    //子进程额外需要监听exitPipe的读端
    close(exitPipe[1]);
    //准备线程池的数据结构
    threadPool_t threadPool;
    int workernum = atoi(conf[2]);

    threadPoolInit(&threadPool,workernum);
    //创建子进程
    makeWorker(&threadPool);

    int sockfd;//初始化tcp连接
    tcpInit(conf[0],conf[1],&sockfd);

    int epfd = epoll_create(1);
    epollAdd(epfd,sockfd);//监听sockfd
    epollAdd(epfd,exitPipe[0]);

    struct epoll_event readyset[2];
    while(1)
    {
        int readynum = epoll_wait(epfd,readyset,2,-1);
        for(int i = 0;i<readynum;++i)
        {
            if(readyset[i].data.fd == sockfd)
            {
                int netfd = accept(sockfd,NULL,NULL);
                pthread_mutex_lock(&threadPool.taskQueue.mutex);
                taskEnQueue(&threadPool.taskQueue, netfd);
                printf("main thred send a task\n");
                pthread_cond_signal(&threadPool.taskQueue.cond);
                pthread_mutex_unlock(&threadPool.taskQueue.mutex);
            }
            else if(readyset[i].data.fd == exitPipe[0])
            {
                printf("threadPool is going to exit\n");
                pthread_mutex_lock(&threadPool.taskQueue.mutex);
                threadPool.exitFlag = 1;
                pthread_cond_broadcast(&threadPool.taskQueue.cond);
                pthread_mutex_unlock(&threadPool.taskQueue.mutex);
                for(int j=0;j<workernum;++j)
                {
                    pthread_join(threadPool.tidArr[j],NULL);
                }
                printf("main thread is closing\n");
                exit(0);


            }
        }
    }

}
